package net.jxtz.jxtzos.spider.process;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.spider.SpiderLogServe;
import net.jxtz.jxtzos.entity.spider.agentsupermarket.detailpage.BidResultNoticeVo;
import net.jxtz.jxtzos.entity.spider.agentsupermarket.indexpage.IndexPageHttpPostEntity;
import net.jxtz.jxtzos.entity.spider.agentsupermarket.indexpage.PurChildClass;
import net.jxtz.jxtzos.entity.spider.agentsupermarket.indexpage.PurProjectList;
import net.jxtz.jxtzos.service.spider.agentsupermarket.AgentSupermarketService;
import net.jxtz.jxtzos.service.spider.agentsupermarket.MyHttpPost;
import net.jxtz.jxtzos.spider.BaseSpiderProcessor;
import net.jxtz.jxtzos.spider.SpiderDefinition;
import net.jxtz.jxtzos.spider.SpiderFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author a123
 */

@Component
@Slf4j
public class AgentSupermarketProcessor implements BaseSpiderProcessor {

    private void indexProcess(Integer page, String serviceType) {
        String s = "https://jxswszjcs.jxzwfww.gov.cn/jx-zjcs-pub/api/bidResultNotice/rest";
        IndexPageHttpPostEntity indexPageHttpPostEntity = new IndexPageHttpPostEntity("2022-03-01", "2022-03-08", "360000", page, "", "", "", "", serviceType, false);
        String s1 = myHttpPost.indexClient(s, indexPageHttpPostEntity);
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject purProjectList = data.getJSONObject("purProjectList");
        PurProjectList purProjectList1 = purProjectList.toJavaObject(PurProjectList.class);
        List<BidResultNoticeVo> bidResultNoticeVos = new ArrayList<>();
        detailsProcess(purProjectList1, bidResultNoticeVos);
        saveBatch(bidResultNoticeVos);
    }

    private void detailsProcess(PurProjectList details, List<BidResultNoticeVo> bidResultNoticeVos) {
        List<PurChildClass> content = details.getContent();
        for (PurChildClass purChildClass : content) {
            String s = myHttpPost.detailsClient(purChildClass.getProjectCode());
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject data = jsonObject.getJSONObject("data");
            BidResultNoticeVo bidResultNoticeVo = data.getJSONObject("bidResultNoticeVo").toJavaObject(BidResultNoticeVo.class);
            JSONObject bsBidResultVo = data.getJSONObject("bsBidResultVo");
            bidResultNoticeVo.setFirstAgentAccount(bsBidResultVo.getString("firstAgentAccount"));
            bidResultNoticeVo.setFirstAgentName(bsBidResultVo.getString("firstAgentName"));
            bidResultNoticeVo.setPrice(bsBidResultVo.getString("price"));
            bidResultNoticeVo.setRegisterTime(bsBidResultVo.getString("registerTime"));
            bidResultNoticeVo.setSpiderLogId(spiderLogId);
            String selectTime = bidResultNoticeVo.getSelectTime();
            String[] split = selectTime.substring(0, selectTime.lastIndexOf(" ")).split("-");
            String month = split[1];
            Month m = LocalDateTime.now().getMonth();
            Month minus = m.minus(2);
            if (minus.getValue() == Integer.parseInt(month)) {
                flag = false;
                break;
            }else {
                log.info("有效数据 ==> " + bidResultNoticeVo);
                bidResultNoticeVos.add(bidResultNoticeVo);
            }
        }
    }

    private void saveBatch(List<BidResultNoticeVo> list){
        for (BidResultNoticeVo bidResultNoticeVo : list) {
            redisTemplate.opsForList().leftPush(CACHE_LIST_KEY, bidResultNoticeVo);
        }
        redisTemplate.expire(CACHE_LIST_KEY, CACHE_TIME_OUT, TimeUnit.SECONDS);
        agentSupermarketService.saveBatch(list);
    }


    private boolean flag = true;

    private final MyHttpPost myHttpPost;

    private final RedisTemplate<String, Object> redisTemplate;

    public final static String CACHE_LIST_KEY = "cache:intermediary-supermarket:processor:BaseProcessor:detailsProcess:BidResultNoticeVo:list_";

    private final static Integer CACHE_TIME_OUT = 6000;

    public final static String SPIDER_NAME = "agentSupermarket";

    private final AgentSupermarketService agentSupermarketService;

    private Long spiderLogId;

    public AgentSupermarketProcessor(MyHttpPost myHttpPost, RedisTemplate<String, Object> redisTemplate, AgentSupermarketService agentSupermarketService) {
        this.myHttpPost = myHttpPost;
        this.redisTemplate = redisTemplate;
        this.agentSupermarketService = agentSupermarketService;

        SpiderFactory instance = SpiderFactory.getInstance();
        instance.putSpiderProcess(SPIDER_NAME, this);
        SpiderDefinition spiderDefinition = new SpiderDefinition();
        spiderDefinition.setSpiderName("江西省中介超市");
        spiderDefinition.setSpiderCode(SPIDER_NAME);
        spiderDefinition.setImgUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180518%2Fb60cabeb62814ac088c54fbf49b9ec7d.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635296918&t=2f70f68f299399952a4ae1ee686db031");
        instance.putSpiderDefinition(SPIDER_NAME, spiderDefinition);
    }

    @Override
    public void start(SpiderLogServe spiderLogServe, SpiderDefinition spiderDefinition) {
        spiderLogId = spiderLogServe.getId();
        log.info("开始爬取，清空缓存 ==> " + redisTemplate.delete(CACHE_LIST_KEY));
//        String[] strings = new String[]{"004", "019", "031"};
        String[] strings = new String[]{"019"};
        for (String string : strings) {
            for (int i = 1; i <= 50; i++) {
                if (flag) {
                    this.indexProcess(i, string);
                }else {
                    flag = true;
                    break;
                }
            }
        }

        Long size = redisTemplate.opsForList().size(CACHE_LIST_KEY);

        log.info("爬取完毕 ==> 长度 ==> " + size);
    }
}
